<!doctype html>
<html dir="ltr" lang="zh-CN">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">


    <script type="text/javascript">
        Function.prototype.delegate = function (delegateFor) {
            console.log(this)
            return delegateFor.apply(null, arguments);
        };

        var Hoge = function () {
            this.open = function () {
                return this.name;
            };
            this.close = function () {
                return 'this is Hoge#close';
            };
            return this;
        };
        var Foo = function () {
            this.name = 'foo';
            this.open = function () {
                return this.name;
            };
            this.close = function () {
                return 'this is Foo#close';
            };
        };

        var hoge = new Hoge;
        var foo = new Foo;
        console.log(hoge.open)
        //alert(hoge.open()); // this is Hoge#open
        alert(hoge.delegate(foo.open)); // this is Foo#open
        //alert(foo.open.delegate(hoge.open)); // this is Hoge#open
    </script>

    <script type="text/javascript">
        var ClassA = function () {
            var _color = "red";
            return {
                getColor: function () {
                    return _color;
                },
                setColor: function (color) {
                    _color = color;
                }
            };
        };
        var delegate = function (client, clientMethod) {
            return function () {
                return clientMethod.apply(client, arguments);
            }
        }
        window.onload = function () {
            var a = new ClassA();
            a.getColor();
            a.setColor("green");
            alert(a.getColor());
            alert(a._color);
//            document.write("<p>执行代理！</p>")
//            var d = delegate(a, a.setColor);
//            d("blue");
//            document.write("<p>执行完毕！</p>")
//            a.getColor();
        };
    </script>
    <title>delegate</title>
</head>
<body>
</body>
</html>
